// import { useState } from 'react';

import { App as AntdApp } from 'antd';
import GridLayout from 'react-grid-layout';
import 'react-grid-layout/css/styles.css';
import 'react-resizable/css/styles.css';

import './App.css';
import { useEffect, useRef, useState } from 'react';
// import GridLayout from './components/GridLayout';

function App() {
  // const [count, setCount] = useState(0);
  const [draggingItem, setDraggingItem] = useState<any>(null);
  const [containerSize, setContainerSize] = useState({
    width: 1200,
    height: 234
  });
  const isDragging = useRef(false);
  const [layout, setLayout] = useState<GridLayout.Layout[]>([
    {
      i: 'a',
      x: 0,
      y: 0,
      w: 4,
      h: 4,
      maxW: 12,
      maxH: 12,
      static: false
    }
  ]);

  // 模拟可拖拽项目数据
  const draggableItems = [
    { id: 'item1', type: 'text', content: '文本块', color: 'skyblue' },
    { id: 'item2', type: 'image', content: '图片块', color: 'pink' },
    { id: 'item3', type: 'chart', content: '图表块', color: '#f0f0f0' }
  ];

  // 监听窗口大小变化
  useEffect(() => {
    const updateWidth = () => {
      const container = document.getElementById('grid-container');
      if (container) {
        setContainerSize({
          width: container.offsetWidth,
          height: (container.offsetHeight - 12 * 13) / 12
        });
      }
    };

    window.addEventListener('resize', updateWidth);
    updateWidth(); // 初始调用

    return () => window.removeEventListener('resize', updateWidth);
  }, []);

  // 布局变化时的回调
  const onLayoutChange = (newLayout) => {
    console.log('onLayoutChange: ');
    // console.log('newLayouts: ', newLayouts);
    // console.log('newLayout: ', newLayout);
    if (isDragging.current) {
      return;
    }
    setLayout(newLayout);
  };

  // 处理拖入
  const onDrop = (layout, layoutItem, _event) => {
    isDragging.current = true;
    if (draggingItem) {
      // 创建新的网格项
      const newGridItem = {
        i: `${draggingItem.id}-${Date.now()}`,
        x: layoutItem.x,
        y: layoutItem.y,
        w: 4,
        h: 4,
        type: draggingItem.type,
        content: draggingItem.content
      };

      setLayout((pre) => {
        return [...pre, newGridItem];
      });
      setDraggingItem(null);
      console.log('onDrop add new item:');
    }
    isDragging.current = false;
  };

  const onDragStart = (e, item) => {
    isDragging.current = true;
    setDraggingItem(item);
    e.dataTransfer.setData('text/plain', JSON.stringify(item));
  };

  return (
    <AntdApp>
      <div style={{ display: 'flex', height: '100vh' }}>
        <div id="grid-container" style={{ flex: 1, height: '100vh' }}>
          <GridLayout
            layout={layout}
            cols={12}
            width={containerSize.width}
            rowHeight={containerSize.height}
            useCSSTransforms={false}
            isDroppable={true}
            onLayoutChange={onLayoutChange}
            onDrop={onDrop}
            compactType={'horizontal'}
            preventCollision={false}
            margin={[12, 12]}
          >
            {layout.map((item) => {
              return (
                <div
                  key={item.i}
                  style={{ backgroundColor: 'lightblue', height: '100%' }}
                >
                  <h3>项目 {item.i}</h3>
                  <p>
                    位置: ({item.x}, {item.y})
                  </p>
                  <p>
                    尺寸: {item.w}×{item.h}
                  </p>
                </div>
              );
            })}
          </GridLayout>
        </div>
        <div
          style={{
            display: 'flex',
            flexDirection: 'column',
            gap: 12,
            width: 500,
            padding: 12,
            boxSizing: 'border-box',
            borderLeft: '1px solid #eee'
          }}
        >
          {draggableItems?.map((item) => {
            return (
              <div
                className="droppable-element-0"
                draggable
                style={{
                  width: '100%',
                  height: containerSize.height * 4 + 12 * 3,
                  backgroundColor: item.color
                }}
                key={item.id}
                // this is a hack for firefox
                // Firefox requires some kind of initialization
                // which we can do by adding this attribute
                // @see https://bugzilla.mozilla.org/show_bug.cgi?id=568313
                onDragStart={(e) => onDragStart(e, item)}
                onDragEnd={() => {
                  isDragging.current = false;
                }}
              >
                Droppable Element (Drag me!)
              </div>
            );
          })}
        </div>
      </div>
    </AntdApp>
  );
}

export default App;
